﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SCONFIG;
using SDATA;

namespace SABI
{
    public partial class FRM : Form
    {
        #region [CÁC BIẾN CỤC BỘ]

        public static bool IsLogin = false;
        public static bool IsClose = false;
        public static bool IsShowLogin = false;
        public static bool IsShowHome = false;       

        //LANG 
        public static string Lang = "vi";        
        
        
        public static string ConnectString = "";
        public static string DataInfo = ""; //Type Authentication|Server|Database|ID|PASS
        public static string UserName="", UserPass = "";

        // * bool
        public static bool UserRemember = false;
        public static bool IsNegativeStock, IsDiscount, IsCommission, IsNegativeCash, IsLockSalePrice, IsAutoSourceNo;
        public static bool IsTestSalePrice, IsConsecutiveExchange, IsStocked, IsSource, IsLimitDate;
        public static bool MessageQuantityAF3016, MessageQuantityAF3013, MessageQuantityAF4016, MessageQuantityAF4017;
        public static bool MessageUnitPriceAF3016, MessageUnitPriceAF3013, MessageUnitPriceAF4016, MessageUnitPriceAF4017;
        public static bool AutoCompactString, PhoneIsNumber;
        public static bool Approve, UsePriceSheet, IsOverDue, IsOverDueSave, IsOverDueShow, IsPromotion;
        public static bool IsAllObjectID, IsAllAccountID, IsAllBankAccountID, IsAllInventoryID, IsAllVoucherTypeID;

        // * string
        public static string DivisionID = "", Period, SystemDateFormat, ID_User, ID_Group, ID_GroupList, ID_DivisionList;
        public static string Server, Database, GroupID, WareHouseID, CurrencyID, CashAccountID, ReceivedAccountID;
        public static string PayableAccountID, TurnOverAccountID, PrimeCostAccountID, VATInAccountID, VATOutAccountID;
        public static string DifferenceAccountID, LossExchangeAccID, InterestExchangeAccID, VATGroupID, PaymentTermID;
        public static string PreCostAccountID,PreCostAccountID2, CommissionAccountID, StockAccountID, PurchaseAccountID;
        public static string UnitID, InventoryTypeID, MethodID, Report15or48, VATImGroupID, VATImPercent, QuantityDecimals;
        public static string ConvertedDecimals, UnitCostDecimals;

        // * int
        public static int ObjectNameConstraint, TradeNameConstraint, VATNoConstraint, AddressConstraint, TelConstraint;
        public static int MobileConstraint, FaxConstraint, EmailConstraint, WebsiteConstraint, ContactorConstraint;
        public static int ObjectNameAllowNull, TradeNameAllowNull, VATNoAllowNull, AddressAllowNull, TelAllowNull;
        public static int MobileAllowNull, FaxAllowNull, EmailAllowNull, WebsiteAllowNull, ContactorAllowNull;
        
        // *date
        public static DateTime DateDue = DateTime.Now;
        public static string Year = "2014";
        public static string Month = "01";

        //DATA
        public static DataTable dt_Object = new DataTable();
        public static DataTable dt_Inventory = new DataTable();
        public static DataTable dt_PaymentTerm = new DataTable();
        public static DataTable dt_VoucherType = new DataTable();
        public static DataTable dt_Currency = new DataTable();
        public static DataTable dt_VATType = new DataTable();
        public static DataTable dt_VATGroup = new DataTable();
        public static DataTable dt_Division = new DataTable();

        //TEST               

        #endregion
        

        public FRM()
        {
            InitializeComponent();
        }

        public void ReadConfig_ToDatabase()
        {           
            string sql = "SELECT * FROM tb0000";
            DataTable dt = DATA.GetDataTable(sql, FRM.ConnectString, false);
            if (dt == null) { return; }
            FRM.DivisionID = dt.Rows[0]["DefDivisionID"].ToString();
            FRM.Month = dt.Rows[0]["DefTranMonth"].ToString();
            FRM.Year = dt.Rows[0]["DefTranYear"].ToString();            
            FRM.Period = string.Format("{0}/{1}", FRM.Month.PadLeft(2,'0'), FRM.Year);
            FRM.WareHouseID = dt.Rows[0]["WareHouseID"].ToString();
            FRM.CurrencyID = dt.Rows[0]["CurrencyID"].ToString();
            FRM.VATGroupID = dt.Rows[0]["VATGroupID"].ToString();

            FRM.CashAccountID = dt.Rows[0]["CashAccountID"].ToString();
            FRM.ReceivedAccountID = dt.Rows[0]["ReceivedAccountID"].ToString();
            FRM.PayableAccountID = dt.Rows[0]["PayableAccountID"].ToString();
            FRM.TurnOverAccountID = dt.Rows[0]["TurnOverAccountID"].ToString();
            FRM.PrimeCostAccountID = dt.Rows[0]["PrimeCostAccountID"].ToString();
            FRM.StockAccountID = dt.Rows[0]["StockAccountID"].ToString();
            FRM.PurchaseAccountID = dt.Rows[0]["PurchaseAccountID"].ToString();
            FRM.VATInAccountID = dt.Rows[0]["VATInAccountID"].ToString();
            FRM.VATOutAccountID = dt.Rows[0]["VATOutAccountID"].ToString();
            FRM.DifferenceAccountID = dt.Rows[0]["DifferenceAccountID"].ToString();
            FRM.PreCostAccountID = dt.Rows[0]["PreCostAccountID"].ToString();
            FRM.PreCostAccountID2 = dt.Rows[0]["PreCostAccountID2"].ToString();
            FRM.InterestExchangeAccID = dt.Rows[0]["InterestExchangeAccID"].ToString();
            FRM.LossExchangeAccID = dt.Rows[0]["LossExchangeAccID"].ToString();

            FRM.VATImPercent = dt.Rows[0]["VATImPercent"].ToString();
            FRM.VATImGroupID = dt.Rows[0]["VATImGroupID"].ToString();
            FRM.QuantityDecimals = dt.Rows[0]["QuantityDecimals"].ToString()!=""? dt.Rows[0]["QuantityDecimals"].ToString() : "0";
            FRM.ConvertedDecimals = dt.Rows[0]["ConvertedDecimals"].ToString() != "" ? dt.Rows[0]["ConvertedDecimals"].ToString() : "0";
            FRM.UnitCostDecimals = dt.Rows[0]["UnitCostDecimals"].ToString() != "" ? dt.Rows[0]["UnitCostDecimals"].ToString() : "0";
            FRM.IsNegativeStock = dt.Rows[0]["IsNegativeStock"].ToString()!="0"?true:false;
            FRM.PaymentTermID = dt.Rows[0]["PaymentTermID"].ToString();
            FRM.IsDiscount = dt.Rows[0]["IsDiscount"].ToString() != "0" ? true : false;            
            FRM.IsCommission = dt.Rows[0]["IsCommission"].ToString() != "0" ? true : false;
            FRM.CommissionAccountID = dt.Rows[0]["CommissionAccountID"].ToString();
            FRM.IsNegativeCash = dt.Rows[0]["IsNegativeCash"].ToString() != "0" ? true : false;
            FRM.IsLockSalePrice = dt.Rows[0]["IsLockSalePrice"].ToString() != "0" ? true : false;
            FRM.IsAutoSourceNo = dt.Rows[0]["IsAutoSourceNo"].ToString() != "0" ? true : false;
            FRM.IsTestSalePrice = dt.Rows[0]["IsTestSalePrice"].ToString() != "0" ? true : false;
            FRM.IsConsecutiveExchange = dt.Rows[0]["IsConsecutiveExchange"].ToString() != "0" ? true : false;

            FRM.MessageQuantityAF3013 = dt.Rows[0]["MessageQuantityAF3013"].ToString() != "0" ? true : false;
            FRM.MessageQuantityAF3016 = dt.Rows[0]["MessageQuantityAF3016"].ToString() != "0" ? true : false;
            FRM.MessageQuantityAF4016 = dt.Rows[0]["MessageQuantityAF4016"].ToString() != "0" ? true : false;
            FRM.MessageQuantityAF4017 = dt.Rows[0]["MessageQuantityAF4017"].ToString() != "0" ? true : false;
            FRM.MessageUnitPriceAF3013 = dt.Rows[0]["MessageUnitPriceAF3016"].ToString() != "0" ? true : false;
            FRM.MessageUnitPriceAF3016 = dt.Rows[0]["MessageUnitPriceAF3016"].ToString() != "0" ? true : false;
            FRM.MessageUnitPriceAF4016 = dt.Rows[0]["MessageUnitPriceAF4016"].ToString() != "0" ? true : false;
            FRM.MessageUnitPriceAF4017 = dt.Rows[0]["MessageUnitPriceAF4017"].ToString() != "0" ? true : false;
            FRM.AutoCompactString = dt.Rows[0]["AutoCompactString"].ToString() != "0" ? true : false;
            FRM.PhoneIsNumber = dt.Rows[0]["PhoneIsNumber"].ToString() != "0" ? true : false;
            FRM.ObjectNameConstraint = dt.Rows[0]["ObjectNameConstraint"].ToString()!=""?int.Parse(dt.Rows[0]["ObjectNameConstraint"].ToString()):0;
            FRM.TradeNameConstraint = dt.Rows[0]["TradeNameConstraint"].ToString() != "" ?int.Parse(dt.Rows[0]["TradeNameConstraint"].ToString()) : 0;
            FRM.VATNoConstraint = dt.Rows[0]["VATNoConstraint"].ToString() != "" ? int.Parse(dt.Rows[0]["VATNoConstraint"].ToString()) : 0;
            FRM.AddressConstraint = dt.Rows[0]["AddressConstraint"].ToString() != "" ? int.Parse(dt.Rows[0]["AddressConstraint"].ToString()) : 0;
            FRM.TelConstraint = dt.Rows[0]["TelConstraint"].ToString() != "" ? int.Parse(dt.Rows[0]["TelConstraint"].ToString()) : 0;
            FRM.MobileConstraint = dt.Rows[0]["MobileConstraint"].ToString() != "" ? int.Parse(dt.Rows[0]["MobileConstraint"].ToString()) : 0;
            FRM.FaxConstraint = dt.Rows[0]["FaxConstraint"].ToString() != "" ? int.Parse(dt.Rows[0]["FaxConstraint"].ToString()) : 0;
            FRM.EmailConstraint = dt.Rows[0]["EmailConstraint"].ToString() != "" ? int.Parse(dt.Rows[0]["EmailConstraint"].ToString()) : 0;
            FRM.WebsiteConstraint = dt.Rows[0]["WebsiteConstraint"].ToString() != "" ? int.Parse(dt.Rows[0]["WebsiteConstraint"].ToString()) : 0;
            FRM.ContactorConstraint = dt.Rows[0]["ContactorConstraint"].ToString() != "" ? int.Parse(dt.Rows[0]["ContactorConstraint"].ToString()) : 0;
            FRM.ObjectNameAllowNull = dt.Rows[0]["ObjectNameAllowNull"].ToString() != "" ? int.Parse(dt.Rows[0]["ObjectNameAllowNull"].ToString()) : 0;
            FRM.TradeNameAllowNull = dt.Rows[0]["TradeNameAllowNull"].ToString() != "" ? int.Parse(dt.Rows[0]["TradeNameAllowNull"].ToString()) : 0;
            FRM.VATNoAllowNull = dt.Rows[0]["VATNoAllowNull"].ToString() != "" ? int.Parse(dt.Rows[0]["VATNoAllowNull"].ToString()) : 0;
            FRM.AddressAllowNull = dt.Rows[0]["AddressAllowNull"].ToString() != "" ? int.Parse(dt.Rows[0]["AddressAllowNull"].ToString()) : 0;
            FRM.TelAllowNull = dt.Rows[0]["TelAllowNull"].ToString() != "" ? int.Parse(dt.Rows[0]["TelAllowNull"].ToString()) : 0;
            FRM.MobileAllowNull = dt.Rows[0]["MobileAllowNull"].ToString() != "" ? int.Parse(dt.Rows[0]["MobileAllowNull"].ToString()) : 0;
            FRM.FaxAllowNull = dt.Rows[0]["FaxAllowNull"].ToString() != "" ? int.Parse(dt.Rows[0]["FaxAllowNull"].ToString()) : 0;
            FRM.EmailAllowNull = dt.Rows[0]["EmailAllowNull"].ToString() != "" ? int.Parse(dt.Rows[0]["EmailAllowNull"].ToString()) : 0;
            FRM.WebsiteAllowNull = dt.Rows[0]["WebsiteAllowNull"].ToString() != "" ? int.Parse(dt.Rows[0]["WebsiteAllowNull"].ToString()) : 0;
            FRM.ContactorAllowNull = dt.Rows[0]["ContactorAllowNull"].ToString() != "" ? int.Parse(dt.Rows[0]["ContactorAllowNull"].ToString()) : 0;
           
            FRM.UnitID = dt.Rows[0]["UnitID"].ToString();
            FRM.InventoryTypeID = dt.Rows[0]["InventoryTypeID"].ToString();
            FRM.IsStocked = dt.Rows[0]["IsStocked"].ToString() != "0" ? true : false;
            FRM.IsSource = dt.Rows[0]["IsSource"].ToString() != "0" ? true : false;
            FRM.IsLimitDate = dt.Rows[0]["IsLimitDate"].ToString() != "0" ? true : false;
            FRM.MethodID = dt.Rows[0]["MethodID"].ToString();
            FRM.Report15or48 = dt.Rows[0]["Report15or48"].ToString();

            FRM.Approve = dt.Rows[0]["Approve"].ToString() != "0" ? true : false;
            FRM.UsePriceSheet = dt.Rows[0]["UsePriceSheet"].ToString() != "0" ? true : false;
            FRM.IsOverDue = dt.Rows[0]["IsOverDue"].ToString() != "0" ? true : false;
            FRM.IsOverDueSave = dt.Rows[0]["IsOverDueSave"].ToString() != "0" ? true : false;
            FRM.IsOverDueShow = dt.Rows[0]["IsOverDueShow"].ToString() != "0" ? true : false; 
            FRM.IsPromotion = dt.Rows[0]["IsPromotion"].ToString() != "0" ? true : false;
            FRM.IsAllObjectID = dt.Rows[0]["IsAllObjectID"].ToString() != "0" ? true : false;
            FRM.IsAllAccountID = dt.Rows[0]["IsAllAccountID"].ToString() != "0" ? true : false;
            FRM.IsAllBankAccountID = dt.Rows[0]["IsAllBankAccountID"].ToString() != "0" ? true : false;
            FRM.IsAllInventoryID = dt.Rows[0]["IsAllInventoryID"].ToString() != "0" ? true : false;
            FRM.IsAllVoucherTypeID = dt.Rows[0]["IsAllVoucherTypeID"].ToString() != "0" ? true : false;
 
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;

            ReadConfig();
            ReadConfig_ToDatabase();

            while (!IsClose)
            {
                /* KIỂM TRA ĐĂNG NHẬP */
                if (!IsLogin)
                {
                    this.Hide();
                    Form frmDangNhap = new frm0413();
                    frmDangNhap.ShowDialog();
                    if(IsLogin)
                    {
                        Form frmHome = new frmHOME();
                        frmHome.ShowDialog();
                    }
                }
            }
            Close();
        }

        private void timerMain_Tick(object sender, EventArgs e)
        {
            this.Hide();
        }

        public static bool AskBeforeSave, Display, WarnNegativeExport, MessageWhenSaveOK, RefreshData, MessageExWhenSale;
        public static bool Preview, ShowRecentValue, MessageImWhenPurchase, UpdateInventoryName;
        public static string PNK, PXK, PT, PC, DT, PTH, PTNH, PCNH, HDBH, HDMH, HBTL, PNKwm, PXKwm, VCNB;
        public static string ReceivedDeliveryKIT, InventoryStock, InventoryBalance, AssetChangeValue, PBH, PBEquipment;


        public static void ReadConfig()
        {
            // config DATA ==========================================================
            Xmlconfig cgDATA = new Xmlconfig("config_data.xml", true);
            FRM.DataInfo = EncryptSnip2code.Decrypt(cgDATA.Settings["DataInfo"].Value);
            string[] cnnArrary = FRM.DataInfo.Split('|');
            if (cnnArrary.Length == 5)
            {
                if (cnnArrary[0] == "0")//SQL Authentication
                    FRM.ConnectString = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3}", cnnArrary[1], cnnArrary[2], cnnArrary[3], cnnArrary[4]);
                else
                    FRM.ConnectString = string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True", cnnArrary[1], cnnArrary[2]);
            }
            else
                FRM.DataInfo = "";

            // config General ==========================================================
            Xmlconfig cg = new Xmlconfig("config.xml", true);
            Lang = cg.Settings["Lang"].Value;
            if (Lang == "") { Lang = "vi"; }
            
            // USER ĐĂNG NHẬP
            FRM.UserName = cg.Settings["UserName"].Value;
            FRM.UserPass = EncryptSnip2code.Decrypt(cg.Settings["UserPass"].Value);
            FRM.UserRemember = cg.Settings["UserRemember"].boolValue;

            // read config
            FRM.AskBeforeSave = cg.Settings["AskBeforeSave"].boolValue;
            FRM.Display = cg.Settings["Display"].boolValue;
            FRM.WarnNegativeExport = cg.Settings["WarnNegativeExport"].boolValue;
            FRM.MessageWhenSaveOK = cg.Settings["MessageWhenSaveOK"].boolValue;
            FRM.RefreshData = cg.Settings["RefreshData"].boolValue;
            FRM.MessageExWhenSale = cg.Settings["MessageExWhenSale"].boolValue;
            FRM.Preview = cg.Settings["Preview"].boolValue;
            FRM.ShowRecentValue = cg.Settings["ShowRecentValue"].boolValue;
            FRM.MessageImWhenPurchase = cg.Settings["MessageImWhenPurchase"].boolValue;
            FRM.UpdateInventoryName = cg.Settings["UpdateInventoryNam"].boolValue;

            FRM.PNK = cg.Settings["PNK"].Value;
            FRM.PXK = cg.Settings["PXK"].Value;
            FRM.PT = cg.Settings["PT"].Value;
            FRM.PC = cg.Settings["PC"].Value;
            FRM.DT = cg.Settings["DT"].Value;
            FRM.PTH = cg.Settings["PTH"].Value;
            FRM.PTNH = cg.Settings["PTNH"].Value;
            FRM.PCNH = cg.Settings["PCNH"].Value;
            FRM.HDBH = cg.Settings["HDBH"].Value;
            FRM.HDMH = cg.Settings["HDMH"].Value;
            FRM.HBTL = cg.Settings["HBTL"].Value;
            FRM.PNKwm = cg.Settings["PNKwm"].Value;
            FRM.PXKwm = cg.Settings["PXKwm"].Value;
            FRM.VCNB = cg.Settings["VCNB"].Value;
            FRM.ReceivedDeliveryKIT = cg.Settings["ReceivedDeliveryKIT"].Value;
            FRM.InventoryStock = cg.Settings["InventoryStock"].Value;
            FRM.InventoryBalance = cg.Settings["InventoryBalance"].Value;
            FRM.AssetChangeValue = cg.Settings["AssetChangeValue"].Value;
            FRM.PBH = cg.Settings["PBH"].Value;
            FRM.PBEquipment = cg.Settings["PBEquipment"].Value;   

            FRM.DateDue = cg.Settings["DefLoginDate"].Value != "" ? DateTime.Parse(cg.Settings["DefLoginDate"].Value) : DateTime.Now;
            FRM.SystemDateFormat = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
        }
        
        public static void SaveConfig()
        {
            Xmlconfig cgDATA = new Xmlconfig("config_data.xml", true);
            cgDATA.Settings["DataInfo"].Value = EncryptSnip2code.Encrypt(DataInfo);
            cgDATA.Save("config_data.xml");

            Xmlconfig cg = new Xmlconfig("config.xml", true);
            cg.Settings["Lang"].Value = Lang;            
            cg.Settings["UserName"].Value = UserName;
            cg.Settings["UserPass"].Value = EncryptSnip2code.Encrypt(UserPass);
            cg.Settings["UserRemember"].boolValue = UserRemember;

            // save config
            cg.Settings["AskBeforeSave"].boolValue = AskBeforeSave;
            cg.Settings["Display"].boolValue = Display;
            cg.Settings["WarnNegativeExport"].boolValue = WarnNegativeExport;
            cg.Settings["MessageWhenSaveOK"].boolValue = MessageWhenSaveOK;
            cg.Settings["RefreshData"].boolValue = RefreshData;
            cg.Settings["MessageExWhenSale"].boolValue = MessageExWhenSale;
            cg.Settings["Preview"].boolValue = Preview;
            cg.Settings["ShowRecentValue"].boolValue = ShowRecentValue;
            cg.Settings["MessageImWhenPurchase"].boolValue = MessageImWhenPurchase;
            cg.Settings["UpdateInventoryNam"].boolValue = UpdateInventoryName;

            cg.Settings["PNK"].Value = PNK;
            cg.Settings["PXK"].Value = PXK;
            cg.Settings["PT"].Value = PT;
            cg.Settings["PC"].Value = PC;
            cg.Settings["DT"].Value = DT;
            cg.Settings["PTH"].Value = PTH;
            cg.Settings["PTNH"].Value = PTNH;
            cg.Settings["PCNH"].Value = PCNH;
            cg.Settings["HDBH"].Value = HDBH;
            cg.Settings["HDMH"].Value = HDMH;
            cg.Settings["HBTL"].Value = HBTL;
            cg.Settings["PNKwm"].Value = PNKwm;
            cg.Settings["PXKwm"].Value = PXKwm;
            cg.Settings["VCNB"].Value = VCNB;
            cg.Settings["ReceivedDeliveryKIT"].Value = ReceivedDeliveryKIT;
            cg.Settings["InventoryStock"].Value = InventoryStock;
            cg.Settings["InventoryBalance"].Value = InventoryBalance;
            cg.Settings["AssetChangeValue"].Value = AssetChangeValue;
            cg.Settings["PBH"].Value = PBH;
            cg.Settings["PBEquipment"].Value = PBEquipment;
            cg.Settings["DefLoginDate"].Value = DateDue.ToShortDateString();            

            cg.Save("config.xml");
           
        }

        private void FRM_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveConfig();
        }

        public static void loadDATA_Combo()
        {
            string sql = "";
            // lấy đối tượng [ObjectID]
            sql = "SELECT *,DueType FROM tb0045 LEFT JOIN tb0051 ON tb0051.PaymentTermID = tb0045.RePaymentTermID";
            sql += " WHERE tb0045.Disabled=0 ORDER BY tb0045.ObjectID";
            FRM.dt_Object = DATA.GetDataTable(sql, FRM.ConnectString, false);

            // lấy mặt hàng [InventoryID]
            sql = "SELECT InventoryID, InventoryName, UnitID, AccountID, SalesAccountID, I01ID, I02ID, I03ID, I04ID, I05ID, GroupShow, InventoryTypeID FROM tb0054 WHERE tb0054.Disabled=0 ORDER BY tb0054.InventoryID";
            FRM.dt_Inventory = DATA.GetDataTable(sql, FRM.ConnectString, false);
        }

        public static DataTable dt_GET(ref DataTable dt, string sql)
        {
            if (dt == null) { dt = new DataTable(); }
            if (dt.Rows.Count < 1) { dt = FRM.GetDataTable(sql); }
            return dt;
        }

        public static DataTable GetDataTable(string query)
        {
            return DATA.GetDataTable(query, FRM.ConnectString);
        }



    }


}
